package com.money.tracker.generator.utils;

import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 数据库相关工具类
 * <p>
 *
 * @author zhangshuai
 * &#064;@date 2024/10/08
 */
@Component
@Slf4j
public class DataSourceHelper {
    @Resource
    private DynamicDataSourceProperties dataSourceConfig;

    /**
     * 获取当前数据源
     *
     * @return {@link DataSourceProperty }
     */

    public DataSourceProperty getDataSourceProperty() {
        // 拿当前数据源配置
        String peek = DynamicDataSourceContextHolder.peek();
        // 没有的话，取主数据源
        if (StringUtils.isBlank(peek)) {
            peek = dataSourceConfig.getPrimary();
        }
        Map<String, DataSourceProperty> datasource = dataSourceConfig.getDatasource();
        return datasource.get(peek);
    }

    /**
     * 获取所有数据库表
     *
     * @return {@link Object }
     */

    public List<TableInfo> tableList() {
        DataSourceProperty dataSourceProperty = getDataSourceProperty();
        String url = dataSourceProperty.getUrl();
        String username = dataSourceProperty.getUsername();
        String password = dataSourceProperty.getPassword();
        ConfigBuilder config = new ConfigBuilder(null, new DataSourceConfig.Builder(url, username, password).build(), null, null, null, null);
        return config.getTableInfoList();
    }

}
